import { Request, Response, NextFunction } from 'express';
const jwt = require('jsonwebtoken');
const { get, set } = require('../config/redis');

// 扩展Express的Request类型
declare module 'express' {
    interface Request {
        user?: {
            userId: number;
            username: string;
        };
    }
}

interface JwtPayload {
    userId: number;
    username: string;
    iat?: number;
    exp?: number;
}

export const authenticateToken = async (req: Request, res: Response, next: NextFunction) => {
    try {
        const authHeader = req.headers['authorization'];
        if (!authHeader) {
            return res.status(401).json({ code: 0, message: '未提供访问令牌' });
        }

        const token = authHeader.split(' ')[1];
        if (!token) {
            return res.status(401).json({ code: 0, message: '令牌格式错误' });
        }

        // 检查token是否在黑名单中
        const isBlacklisted = await get(`blacklist:${token}`);
        if (isBlacklisted) {
            return res.status(401).json({ code: 0, message: '令牌已失效' });
        }

        const secret = process.env.JWT_SECRET;
        if (!secret) {
            console.warn('JWT_SECRET未配置，使用默认密钥');
        }

        const decoded = jwt.verify(token, secret || 'default_secret') as JwtPayload;
        req.user = {
            userId: decoded.userId,
            username: decoded.username
        };
        next();
    } catch (err) {
        if (err instanceof jwt.TokenExpiredError) {
            return res.status(403).json({ code: 0, message: '令牌已过期' });
        } else if (err instanceof jwt.JsonWebTokenError) {
            return res.status(403).json({ code: 0, message: '无效令牌' });
        }
        console.error('认证中间件错误:', err);
        return res.status(500).json({ code: 0, message: '服务器内部错误' });
    }
};

export const addToBlacklist = async (token: string, expiresIn: number) => {
    // 将token加入黑名单，并设置与JWT相同的过期时间
    await set(`blacklist:${token}`, '1', { EX: expiresIn });
};
